package com.meiqiongproperty.yiguanjia.fragment.home.tenement;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.meiqiongproperty.yiguanjia.R;
import com.meiqiongproperty.yiguanjia.databinding.BxdLayoutBinding;
import com.meiqiongproperty.yiguanjia.fragment.BaseFragment;
import com.meiqiongproperty.yiguanjia.fragment.home.adapter.GridImageAdapter;
import com.meiqiongproperty.yiguanjia.http.api.ApiService;
import com.meiqiongproperty.yiguanjia.http.interfaces.SimpleHttpCallback;
import com.meiqiongproperty.yiguanjia.http.sendJsonModel.SendBxts;
import com.meiqiongproperty.yiguanjia.httpbean.user.ForGetpassword;
import com.meiqiongproperty.yiguanjia.ui.picker.DataPickerDialog;
import com.meiqiongproperty.yiguanjia.utils.FullyGridLayoutManager;
import com.meiqiongproperty.yiguanjia.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 投诉表扬
 *
 * @version V1.0
 * @packge com.meiqiongproperty.yiguanjia.fragment.home.tenement
 * @User ChenJing
 * @Date 2017/5/7
 */

public class BXDFragment extends BaseFragment {
    BxdLayoutBinding binding;
    //private PhotoPresenter mPhotoPresenter;
    private ArrayList<String> selectedPhotos = new ArrayList<>();
    private List<LocalMedia> selectList = new ArrayList<>();
    Dialog chooseDialog;
    private GridImageAdapter adapter;
    private int maxSelectNum = 9;
    int selectPic=0;
    int type=0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.bxd_layout, container, false);
        //mPhotoPresenter = new PhotoPresenter(getActivity(), "feedback");
        binding.setClick(this);
        initView();
        return binding.getRoot();
    }

    private void initView() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(getActivity(), 4, GridLayoutManager.VERTICAL, false);
        binding.imgGrid.setLayoutManager(manager);
        adapter = new GridImageAdapter(getActivity(), onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        binding.imgGrid.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                LocalMedia media = selectList.get(position);
                String pictureType = media.getPictureType();
                int mediaType = PictureMimeType.pictureToVideo(pictureType);
                switch (mediaType) {
                    case 1:
                        // 预览图片
                        PictureSelector.create(BXDFragment.this).externalPicturePreview(position, selectList);
                        break;
                    case 2:
                        // 预览视频
                        PictureSelector.create(BXDFragment.this).externalPictureVideo(media.getPath());
                        break;
                    case 3:
                        // 预览音频
                        PictureSelector.create(BXDFragment.this).externalPictureAudio(media.getPath());
                        break;
                }
            }
        });

        binding.addContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length()==0){
                    binding.discriptionNumber.setText("0/200");
                    return;
                }
                binding.discriptionNumber.setText(s.length()+"/200");
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length()>200){
                    s.delete(s.length()-1,s.length());
                    Toast.makeText(getActivity(),"超过字数限制",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void confirmRepairClick(View view){
        int count=selectList.size();
        if (type==0){
            Toast.makeText(getActivity(),"请选择类型",Toast.LENGTH_LONG).show();
            return;
        }
        if (binding.addContent.getEditableText().toString().equals("")){
            Toast.makeText(getActivity(),"请输入要投诉或者表扬的信息",Toast.LENGTH_LONG).show();
            return;
        }
        if (count==0){
            Toast.makeText(getActivity(),"请添加图片",Toast.LENGTH_LONG).show();
            return;
        }
        if (count>3){
            Toast.makeText(getActivity(),"最多添加三张图片",Toast.LENGTH_LONG).show();
            return;
        }

        SendBxts sendBxts=new SendBxts();
        sendBxts.setRoomID(Utils.getRoomID(getActivity()));
        sendBxts.setType(type);
        sendBxts.setContent(binding.addContent.getEditableText().toString());
        sendBxts.setPicCount(count);
        sendBxts.setToken(Utils.getToken(getActivity()));
        switch (count){
            case 1:
                sendBxts.setImages1(new File(selectList.get(0).getPath()));
                break;
            case 2:
                sendBxts.setImages1(new File(selectList.get(0).getPath()));
                sendBxts.setImages1(new File(selectList.get(1).getPath()));
                break;
            case 3:
                sendBxts.setImages1(new File(selectList.get(0).getPath()));
                sendBxts.setImages1(new File(selectList.get(1).getPath()));
                sendBxts.setImages1(new File(selectList.get(2).getPath()));
                break;
        }
        ApiService.feedback(getActivity(), new SimpleHttpCallback<ForGetpassword>() {
            @Override
            public void onNext(ForGetpassword forGetpassword) {
                Toast.makeText(getActivity(),"提交成功",Toast.LENGTH_LONG).show();
                sendKeyBackEvent();
            }
        },Utils.getRequestBody(sendBxts));
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            PictureSelector.create(getActivity())
                    .openGallery(PictureMimeType.ofImage())
                    .maxSelectNum(9)
                    .minSelectNum(1)
                    .selectionMode(PictureConfig.MULTIPLE)
                    .previewImage(true)
                    .compressGrade(Luban.THIRD_GEAR)
                    .isCamera(true)
                    .enableCrop(false)
                    .compress(true)
                    .compressMode(PictureConfig.LUBAN_COMPRESS_MODE)
                    .glideOverride(160, 160)
                    .previewEggs(true)
                    .circleDimmedLayer(true)
                    .withAspectRatio(1,1)
                    .hideBottomControls(false)
                    .isGif(false)
                    .freeStyleCropEnabled(true)
                    .showCropFrame(false)
                    .showCropGrid(false)
                    .openClickSound(true)
                    .selectionMedia(selectList)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    Toast.makeText(getActivity(),"=="+selectList.size(),Toast.LENGTH_SHORT).show();
                    selectPic=selectList.size();
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }


//
//    public void initView() {
//        if (Build.VERSION.SDK_INT >= 23) {
//            if (ContextCompat.checkSelfPermission(getActivity(),
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                    != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getActivity(),
//                    Manifest.permission.CAMERA)
//                    != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(getActivity(),
//                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
//                        1);
//            }
//        }
//
//        mPhotoPresenter.initView(binding.imgGrid);
//        binding.imgGrid.setMaxItemPerRow(4);
//        binding.imgGrid.setItemMarginHor(7f);
//        binding.imgGrid.setItemMarginVer(7f);
//        mPhotoPresenter.updateImgGrid();
//    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Permission OK
            } else {
                // Permission Denied
                Toast.makeText(getActivity(), "请在设置中开启存储和拍照权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

//    @Override
//    public void onActivityResult(FragmentActivity activity, int requestCode, int resultCode, Intent data) {
//        LogUtil.d("onActivityResult1asd=======" + data);
//        if (requestCode == PhotoPickupActivity.REQUEST_CODE) {
//            if (resultCode == RESULT_OK) {
//                LogUtil.d("onActivityResult1=======" + data);
//                if (PhotoPickupActivity.getSelectedImgPros(data) != null) {
//                    mPhotoPresenter.pickPhotoResult(data);
//                }
//            }
//        } else if (requestCode == ImageLookActivity.REQUEST_CODE) {
//            LogUtil.d("onActivityResult1=======" + data);
//            if (resultCode == RESULT_OK) {
//                if (data != null) {
//                    mPhotoPresenter.lookImageResult(data);
//                }
//            }
//        }
//
//    }
//
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == PhotoPickupActivity.REQUEST_CODE) {
//            if (resultCode == RESULT_OK) {
//                LogUtil.d("onActivityResult1=======" + data);
//                if (PhotoPickupActivity.getSelectedImgPros(data) != null) {
//                    mPhotoPresenter.pickPhotoResult(data);
//                }
//            }
//        } else if (requestCode == ImageLookActivity.REQUEST_CODE) {
//            LogUtil.d("onActivityResult1=======" + data);
//            if (resultCode == RESULT_OK) {
//                if (data != null) {
//                    mPhotoPresenter.lookImageResult(data);
//                }
//            }
//        }
//    }

    public void CheckType(View view) {
        List<String> type = new ArrayList<>();
        type.add("投诉/建议");
        type.add("表扬");
        showChooseDialog(type);
    }


    private void showChooseDialog(List<String> mlist) {
        final DataPickerDialog.Builder builder = new DataPickerDialog.Builder(getActivity());
        chooseDialog = builder.setData(mlist).setSelection(1).setTitle("取消")
                .setOnDataSelectedListener(new DataPickerDialog.OnDataSelectedListener() {
                    @Override
                    public void onDataSelected(String itemValue, int position) {
                        binding.typeText.setText(itemValue);
                        if (position==0){
                            type=4;
                        }else if(position==1){
                            type=3;
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                }).create();

        chooseDialog.show();
    }
}
